<template>
	<page-meta :page-font-size="baseFontSize + 'rpx'" :root-font-size="baseFontSize + 'rpx'"></page-meta>
	<view style="height: 100%">
		<view class="addr flex align-center">
			<view>当前位置</view>
			<view class="location flex-sub text-right">{{ longitude }},{{ latitude }}</view>
			<view class="refresh" @tap="startLocationUpdate">刷新</view>
		</view>
		<view class="view-fixed">
			<image src="/static/images/map-addr-bg.png" mode="widthFix"></image>
			<view class="total">今日巡查点 {{ num || 0 }}</view>
			<view class="view-title-info">
				<view>已完成 {{ finishNum || 0 }} / 未完成 {{ notNum || 0 }}</view>
			</view>
			<view class="changetab" @tap="changetab">{{ tab == 1 ? '切换列表' : '切换地图' }}</view>
		</view>
		<block v-if="tab == 1">
			<map id="myMap" style="width: 100vw; height: 120vh" :latitude="latitude" :longitude="longitude"
				:markers="markers" :circles="circles" @markertap="markertap" show-location></map>
		</block>
		<view class="list" v-else>
			<view class="list-hd flex ">
				<view class="flex-sub">巡查点名字</view>
				<view class="flex-sub">距离当前距离(m)</view>
			</view>
			<view class="list-bd">
				<view class="list-bd-tr flex" :class="{ 'active': item.active }" v-for="(item, index) in  patrolList "
					:key="index" @click='handleSelectPatrol(item)'>
					<view class="flex-sub">{{ item.inspName }}({{ item.reportState !== -1 ? '已巡' : '未巡' }})</view>
					<view class="flex-sub">{{ item.distance }}</view>
					<uni-icons type="forward" size="16" color="#597EF7"></uni-icons>
				</view>
			</view>
		</view>
		<view class="submit-btn">
			<!-- <van-button type="primary" block custom-class="submit" style="width: 250rpx" color="#229953" @tap.native="onSubmit">案卷上报</van-button> -->
			<!-- <van-button type="primary" block custom-class="submit" style="width: 250rpx" color="#229953" @tap.native="onSubmit1">日报表</van-button> -->
			<view class="record" @tap="navTo('/pages/richangxuncha/xunchajilu')">
				<image src="/static/images/clock.png" mode="widthFix"></image>
				<view>巡查记录</view>
			</view>
			<button @tap="startPatrol" v-if="!staring" class="cu-btn block bg-blue lg">开始巡查</button>
			<button @tap="handerPartrol" v-else class="cu-btn cu-btn-plain block lg">巡查点上报</button>
		</view>
	</view>
</template>

<script>
import http from '../../utils/http.js'
import util from '../../utils/util.js'
import { getPatrolMobileFinishInfoTaskApi, startPatrolApi } from '@/api/system/changxiao.js'
import { patrolTaskMobile } from '@/api/system/xuncha.js'
export default {
	data() {
		return {
			locationArr: [],
			taskLists: [],
			patrolPointItem: {},
			staring: false, //开始巡检
			latitude: 30.54251,
			longitude: 119.977401,
			markers: [],
			notNum: 0,
			finishNum: 0,
			distance: 500,
			startTaskId: null,

			// circle: [],
			circles: [
				{
					latitude: 30.31974,
					longitude: 120.1421,
					radius: 100,
					fillColor: '#AACCEE32',
					color: '#AACCEE',
					strokeWidth: 2
				}
			],

			patrolList: [],
			wxmap: null,
			num: '',
			finishDayTaskObj: {},
			tab: 1
		}
	},
	computed: {
		baseFontSize() {
			return this.$store.getters.fontSize
		}
	},
	/**
	 * 生命周期函数--监听页面加载
	 */ onLoad(options) {
		// this.data.wxmap = wx.createMapContext("myMap");
		// console.log(this.data.wxmap);
	},
	/**
	 * 生命周期函数--监听页面初次渲染完成
	 */
	onReady() { },
	onShow() {
		this.staring = false
		this.getPatrolTask()
		// 获取位置
		this.startLocationUpdate()
		// 获取巡查任务
		this.getTemporaryByCuringUtil()
	},
	/**
	 * 生命周期函数--监听页面隐藏
	 */
	onHide() {
		uni.stopLocationUpdate({
			success: res => {
				console.log('%c [ stopLocationUpdate ]-139', 'font-size:13px; background:pink; color:#bf2c9f;', res)
			},
			fail: err => {
				console.log(err)
			}
		})
	},
	/**
	 * 生命周期函数--监听页面卸载
	 */
	onUnload() {
		uni.stopLocationUpdate({
			success: res => {
				console.log('%c [ stopLocationUpdate ]-139', 'font-size:13px; background:pink; color:#bf2c9f;', res)
			},
			fail: err => {
				console.log(err)
			}
		})
	},
	/**
	 * 页面相关事件处理函数--监听用户下拉动作
	 */
	onPullDownRefresh() { },
	/**
	 * 页面上拉触底事件的处理函数
	 */
	onReachBottom() { },
	/**
	 * 用户点击右上角分享
	 */
	onShareAppMessage() { },
	methods: {
		startPatrol() {
			if (this.patrolPointItem && this.patrolPointItem.id) {
				let { id: patrolPointId, inspName } = this.patrolPointItem
				let selectedTask = this.findtask(patrolPointId)
				let { id: taskId, taskNum } = selectedTask
				this.staring = true
				startPatrolApi({
					taskId,
					taskNum
				}).then(res => {
					this.startTaskId = res.data
				})
			} else {
				this.staring = false
				uni.showToast({
					title: '还没到巡查点附近，不能提交数据',
					icon: 'error',
					duration: 1500,
					mask: true
				})
			}
		},
		getPatrolTask() {
			getPatrolMobileFinishInfoTaskApi().then(res => {
				this.finishDayTaskObj = res.data
			})
		},
		navTo(path) {
			this.$tab.navigateTo(path)
		},
		/**
		 * 生命周期函数--监听页面显示
		 */
		rad(d) {
			return (d * Math.PI) / 180
		},

		getDistance(lng1, lat1, lng2, lat2) {
			var radLat1 = this.rad(lat1)
			var radLat2 = this.rad(lat2)
			var a = radLat1 - radLat2
			var b = this.rad(lng1) - this.rad(lng2)
			var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)))
			s = s * 6378.137 //地球半径
			s = Math.round(s * 10000) / 10000
			return s //返回数值单位：公里
		},

		startLocationUpdate() {
			uni.startLocationUpdate({
				success: res => {
					//成功的逻辑
					uni.onLocationChange(data => {
						console.log('%c [ data ]-230', 'font-size:13px; background:pink; color:#bf2c9f;', data)
						//获取实时的定位信息
						// this.data.wxmap.getRegion({
						//   success: res => {
						//     console.log('getRegion>>>', res);
						//     let lng1 = res.northeast.longitude;
						//     let lat1 = res.northeast.latitude;
						//     let lng2 = res.southwest.longitude;
						//     let lat2 = res.southwest.latitude;
						//     let longitude = lng1 - lng2;
						//     let latitude = lat1 - lat2;
						//     let flag = longitude > latitude ? true : false;
						//     let radius = 0;
						//     //计算得到短边，然后再通过*1000转变为m，除2得到半径，*0.8优化显示，让圈圈只占界面的80%
						//     if (flag) {
						//       radius = this.getDistance(lng1, lat1, lng1, lat2) * 1000 / 2 * 0.8;
						//     } else {
						//       radius = this.getDistance(lng1, lat1, lng2, lat1) * 1000 / 2 * 0.8;
						//     }
						//     console.log('radius>>>', radius);
						//     this.setData({
						//       "circles[0].radius": radius
						//     });
						//     console.log(this.data);
						//   },
						//   fail: errs => {
						//     console.log(errs);
						//   }
						// });
						// this.setData({
						// 	longitude: data.longitude,
						// 	latitude: data.latitude,
						// 	'circles[0].longitude': data.longitude,
						// 	'circles[0].latitude': data.latitude
						// });
						let longitude = data.longitude.toFixed(6)
						let latitude = data.latitude.toFixed(6)
						this.locationArr.push({
							latitude,
							longitude
						})
						uni.setStorageSync('locationArr', this.locationArr)
						this.longitude = longitude
						this.latitude = latitude
						this.circles[0].longitude = data.longitude
						this.circles[0].latitude = data.latitude
						this.distanceCalculation(data.longitude, data.latitude)
					})
				},
				fail: err => {
					console.log(err)
					//失败的逻辑
					//1.wx.showModal引导用户授权
					//2.通过wx.openSetting让用户开启权限
					uni.showModal({
						//引导用户授权
						title: '提示',
						content: '请打开定位权限',
						confirmText: '设置',
						cancelText: '取消',
						showCancel: false,
						success: res => {
							//点击“确认”时打开设置页面
							if (res.confirm) {
								uni.openSetting({
									//打开设置页面让用户选择权限
									success: res => {
										console.log(res)
										if (res.authSetting['scope.userLocation'] == true) {
											uni.onLocationChange(data => {
												//实时获取用户最新的经纬度信息
												console.log(data)
											})
										}
									}
								})
							} else {
								//取消打开设置授权页面
								uni.showToast({
									title: '取消授权',
									icon: 'none'
								})
							}
						}
					})
				}
			})
		},

		// 计算距离
		distanceCalculation(log, lat) {
			let patrolList = this.patrolList
			if (patrolList.length > 0) {
				let calcDistancePartrol = patrolList.map((item, index) => {
					item.distance = util.getDistance(log, lat, item.longitude, item.latitude)

					// if (+this.distance >= +item.distance) {

					//   this.patrolPointItem = item

					//   //  isDone==0 打点
					//   if (!item.isDone) {
					//     //   this.getDot(item, index)
					//   }
					// }
					return {
						...item
					}
				})
				calcDistancePartrol.sort((a, b) => a.distance - b.distance)
				// for (let i = 0; i < calcDistancePartrol.length; i++) {
				//   if (calcDistancePartrol[i].reportState == -1) {
				//     this.patrolPointItem = calcDistancePartrol[i]
				//     break
				//   }
				// }
				this.patrolList = calcDistancePartrol.map((item,index)=>{
					return {
						...item,
						active:index==0?true:false
					}
				})
				console.log('%c [ this.patrolList ]-319', 'font-size:13px; background:pink; color:#bf2c9f;', this.patrolList)
				this.patrolPointItem = calcDistancePartrol[0]
			}
		},
		handleSelectPatrol(item) {
			this.patrolList.map(item => {
				item.active = false
			})
			item.active = true
			this.patrolPointItem = item
		},
		handerPartrol() {
			//开始巡查

			if (this.patrolPointItem && this.patrolPointItem.id) {
				let { id: patrolPointId, inspName, facilityId } = this.patrolPointItem
				let selectedTask = this.findtask(patrolPointId)

				let { id, taskNum, facilityName } = selectedTask
				this.navTo(
					`/pages/addForm/xuanjiandianshangbao?patrolPointId=${patrolPointId}&startTaskId=${this.startTaskId
					}&inspName=${inspName}&taskNum=${taskNum}&id=${id}&facilityName=${facilityName}&facilityId=${facilityId}`
				)
				uni.stopLocationUpdate({
					success: res => {
						console.log(res)
					},
					fail: err => {
						console.log(err)
					}
				})
			} else {
				uni.showToast({
					title: '还没到巡查点附近，不能提交数据',
					icon: 'error',
					duration: 1500,
					mask: true
				})
			}
		},

		findtask(patrolPointId) {
			return this.taskLists.find(item => {
				if (item.patrolPointDOList) {
					return item.patrolPointDOList.find(subitem => subitem.id === patrolPointId)
				}
			})
		},

		// 打点
		getDot(item, index) {
			let data = {
				id: item.id,
				userName: uni.getStorageSync('userInfo').accountName,
				userUuid: uni.getStorageSync('userInfo').accountUuid,
				isDone: 1
			}
			http.wxRequest(
				'POST',
				'/temporary/doPatrol',
				data,
				res => {
					if (res.errcode == 0) {
						uni.showToast({
							title: '打点成功',
							duration: 1500,
							mask: true
						})
					} else {
						uni.showToast({
							title: res.errmsg,
							duration: 1500,
							mask: true
						})
					}
				},
				err => {
					console.log(err)
				}
			)
		},

		// 获取巡查任务
		getTemporaryByCuringUtil() {
			let _this = this
			patrolTaskMobile({
				pageNo: 1,
				pageSize: 10000,
				taskType: 1
			}).then(res => {
				console.log('%c [ res ]-347', 'font-size:13px; background:pink; color:#bf2c9f;', res)
				if (res.code == 0) {
					_this.taskLists = res.data.list
					_this.patrolList = []
					res.data.list.map(item => {
						if (item.patrolPointDOList && item.patrolPointDOList.length > 0) {
							item.patrolPointDOList.map(pitem => {
								_this.patrolList.push(pitem)
							})
						}
					})
					console.log('%c [ _this.patrolList ]-350', 'font-size:13px; background:pink; color:#bf2c9f;', _this.patrolList)

					if (_this.patrolList && _this.patrolList.length > 0) {
						let markers = []
						let circles = []
						_this.patrolList.map(item => {
							markers.push({
								id: item.id,
								inspName: item.inspName,
								longitude: item.longitude,
								latitude: item.latitude,
								iconPath: item.reportState != -1 ? '/static/mapicon/bridgeL.png' : '/static/mapicon/bridgeH.png',
								width: 40,
								height: 40,
								callout: {
									content: item.inspName,
									display: 'ALWAYS',
									textAlign: 'center',
									fontSize: 13,
									borderRadius: 5,
									bgColor: '#000',
									color: '#fff',
									padding: 6
								}
							})
						})
						// _this.num = res.data.total
						_this.num = _this.patrolList.length
						_this.markers = markers

						// _this.notNum = res.data.unfinishedNum
						// _this.finishNum = res.data.completedNum
						_this.notNum = _this.patrolList.filter(item => item.reportState == -1).length
						_this.finishNum = _this.patrolList.filter(item => item.reportState != -1).length
					}
				}
			})
		},

		markertap(e) {
			let markerId = e.detail.markerId
			let { latitude, longitude, inspName } = this.markers.find(item => item.id == markerId)
			uni.openLocation({
				latitude: Number(latitude),
				longitude: Number(longitude),
				name: inspName,
				success: function () {
					console.log('success')
				}
			})
		},

		onSubmit() {
			uni.navigateTo({
				url: '/pages/anJuanShangBao/anJuanShangBao?query=' + 'case_data_source_inspection'
			})
		},

		onSubmit1() {
			uni.navigateTo({
				url: '/pages/riBaoBiao/riBaoBiao'
			})
		},
		changetab() {
			this.tab = this.tab == 1 ? 2 : 1
		}
	}
}
</script>
<style>
@import './xunJianMap.css';
</style>
